import axios, {
  type InternalAxiosRequestConfig,
  type AxiosError,
  type AxiosRequestConfig
} from 'axios'

interface AxiosRequestConfigEx extends AxiosRequestConfig {
  donNotShowLoading?: boolean
}

export interface UsersType {
  avatar?: string;
  deptId?: string;
  email: string;
  gender?: number;
  id?: string;
  mobile: string;
  nickname: string;
  password: string;
  roleIds?: number[];
  status?: number;
  username: string;
  [property: string]: any;
}

const instance = axios.create({
  // 基本的url地址
  baseURL: import.meta.env.VITE_BASE_PATH,
  // 超时时间
  timeout: 2000
})

// http request 拦截器
instance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 使用 set 方法来设置 headers
    config.headers.set('Content-Type', 'application/json')
    // 手动设置用户token
    const token =
      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySW5mbyI6eyJ1c2VySWQiOjExMTYsInVzZXJuYW1lIjoic3VjaGVuZ2ZlbmciLCJuaWNrbmFtZSI6InN1Y2hlbmdmZW5nIiwiZGVwdElkIjoxOCwicm9sZXMiOiIifSwiaXNzIjoiZHlzNjIzMCIsImV4cCI6MTcyOTY5MDM5MCwibmJmIjoxNzI5NjU0NDAwLCJpYXQiOjE3Mjk2NTQzOTB9.lsJTVC7iJfIKKNvU-i3Oq-QORUoNBlHG2SATK0uNo_4'
    config.headers.set('Authorization', token)
    return config
  },
  (error: AxiosError) => {
    // 请求报错
    Promise.reject(error)
  }
)

instance.interceptors.response.use(
  (response) => {
    // 响应成功时做一些处理
    console.log('响应拦截器: ', response)
    return response
  },
  (error) => {
    // 统一处理错误信息
    if (error.response.status === 401) {
      // 如果是 401 错误，可能是未授权，跳转到登录页面
      window.location.href = '/login'
    } else if (error.response.status === 500) {
      // 服务器错误
      console.error('服务器错误')
    }

    return Promise.reject(error)
  }
)

// 服务请求
export const service = (config: AxiosRequestConfigEx) => {
  return instance.request(config).then((response) => {
    return response.data
  })
  // .catch(error => console.error(error));
}

// 用户分页列表
export const requestGetUsersPage = (params: any) => {
  return service({
    method: 'get', // 指定请求方法
    url: '/users/page', // 请求的 URL
    params // 查询参数
  })
}


/**
 * 添加用户
 */
export const addUser = (data: any) => {
  return service({
    method: 'post',
    url: '/users',
    data
  })
}

/**
 * 修改用户的数据
 */
export const editUser = (userId: number, data: any) => {
  return service({
    method: 'put',
    url: `/users/${userId}`,
    data
  })
}

/**
 * 修改用户状态
 */
export const editUserStaus = (userId: string, status: number) => {
  return service({
    method: 'patch',
    url: `/users/${userId}/status`,
    params: { status }
  })
}

/**
 * 删除用户
 */
export const delUser = () => {
  return service({
    method: 'post',
    url: `/user/del`
  })
}

/**
 * 登录用户
 */
export const userLogin = (data: any) => {
  return service({
    method: 'post',
    url: `/auth/login`,
    data
  })
}
